#!/bin/bash
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: yandi-host-shrink-qcow2.sh
# author: david921518@qq.com

# 1. enable NBD on the host
/sbin/modprobe nbd max_part=8

# 2. connect the QCOW2 as a network block device
qemu-nbd --connect=/dev/nbd0 kpcos-yandi-1.02-nocloud-arm64-40g.qcow2
sleep 0.1

# 3. mount the partition from the VM
mount /dev/nbd0p1 /mnt/yandi/
sleep 0.1

# 4. trim filesystem
/sbin/fstrim -v /mnt/yandi

# 5. unmount and disconnect QCOW2
umount /mnt/yandi/
qemu-nbd --disconnect /dev/nbd0
#rmmod nbd

# 6. shrink qcow2 image
qemu-img convert -O qcow2 kpcos-yandi-1.02-nocloud-arm64-40g.qcow2 shrink-kpcos-yandi-1.02-nocloud-arm64-40g.qcow2

# restart system
#poweroff

